package com.clean.notification.device;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.SPUtils;
import com.google.android.gms.ads.identifier.AdvertisingIdClient;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;

import java.io.IOException;
import java.util.List;
import java.util.Observer;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.locks.ReentrantLock;

public class DeviceInfoPhone {

    public static final int NETWORK_TYPE_WIFI = 0;
    public static final int NETWORK_TYPE_MOBILE = 1;

    public static final String INSTALLATION_ID_KEY = "installation.id";
    public static final String GOOGLE_AD_ID = "google.advertising.id";

    private static DeviceInfoPhone instance = new DeviceInfoPhone();
    ;
    private final ReentrantLock installationIdLock = new ReentrantLock();
    private volatile String deviceId;
    private volatile String gaid;
    private int networkState;
    private boolean hasRequested;

    public static DeviceInfoPhone getInstance() {
        return instance;
    }

    private DeviceInfoPhone() {
    }

    @Nullable
    public synchronized String getDeviceId() {
        if (!TextUtils.isEmpty(deviceId)) {
            return deviceId;
        }
        deviceId = SPUtils.getInstance().getString(INSTALLATION_ID_KEY);

        if (deviceId == null || deviceId.isEmpty()) {
            deviceId = createInstallationUUID();
        }

        Log.e("changfei11", "getDeviceId deviceId:" + deviceId);
        return deviceId;
    }

    /**
     * 每次进程重启后尝试获取一次gaid
     *
     * @param context
     */
    public void tryGetAndReportGaid(final Context context) {
        if (!TextUtils.isEmpty(gaid)) {
            return;
        } else {
            gaid = SPUtils.getInstance().getString(GOOGLE_AD_ID);
        }
        if (!hasRequested && TextUtils.isEmpty(gaid)) {
            hasRequested = true;
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    AdvertisingIdClient.Info adInfo = null;
                    long t1 = System.currentTimeMillis();
                    try {
                        adInfo = AdvertisingIdClient.getAdvertisingIdInfo(context.getApplicationContext());
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (GooglePlayServicesNotAvailableException e) {
                        e.printStackTrace();
                    } catch (GooglePlayServicesRepairableException e) {
                        e.printStackTrace();
                    }
                    if (adInfo != null) {
                        gaid = adInfo.getId();
                        SPUtils.getInstance().put(DeviceInfoPhone.GOOGLE_AD_ID, gaid);
                    }
                }
            }.start();
        }
    }

    private final List<Observer> observers = new CopyOnWriteArrayList<>();
    private boolean isUpdating = false;


    @SuppressLint("ApplySharedPref")
    private String createInstallationUUID() {
        this.installationIdLock.lock();
        try {
            String uuid = SPUtils.getInstance().getString(INSTALLATION_ID_KEY);
            if (uuid == null || uuid.isEmpty()) {
//        uuid = getDeviceIdOld(BaseApp.inst);
                uuid = "R" + UUID.randomUUID().toString();
                SPUtils.getInstance().put(INSTALLATION_ID_KEY, uuid);
            }
            return uuid;
        } finally {
            this.installationIdLock.unlock();
        }
    }

    //android 12会出现这种情况，视为无效
    private boolean isValid(String gaid) {
        if (!TextUtils.isEmpty(gaid)) {
            for (int i = 0; i < gaid.length(); i++)// 避免全0
            {
                if (gaid.charAt(i) != '0' && gaid.charAt(i) != '-') {
                    return true;
                }
            }
        }
        return false;
//    return !TextUtils.isEmpty(gaid) &&
//        !("00000000-0000-0000-0000-000000000000".equals(gaid)); //android 12会出现这种情况，视为无效
    }

    public int getNetworkState(Context context) {
        if (context != null) {
            ConnectivityManager conManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo wifiInfo = conManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (wifiInfo == null || wifiInfo.getState() == NetworkInfo.State.CONNECTED || wifiInfo.getState() == NetworkInfo.State.CONNECTING) {
                networkState = NETWORK_TYPE_WIFI;
            } else {
                networkState = NETWORK_TYPE_MOBILE;
            }
        }
        return networkState;
    }

    public boolean isWifiConnected(Context context) {
        return getNetworkState(context) == NETWORK_TYPE_WIFI;
    }

}
